package com.m3958.firstgwt.server.service;

import java.util.Date;

import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.persistence.EntityManager;
import javax.persistence.Query;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.persist.Transactional;
import com.google.inject.persist.UnitOfWork;
import com.m3958.firstgwt.client.types.ActiveMqSubject;
import com.m3958.firstgwt.server.dao.WorkFlowProjectDao;
import com.m3958.firstgwt.server.model.User;
import com.m3958.firstgwt.server.model.WorkFlowProject;

public class ChangeLogConsumerThread  extends Thread{
	
    private String user = ActiveMQConnection.DEFAULT_USER;
    private String password = ActiveMQConnection.DEFAULT_PASSWORD;
    private String url = ActiveMQConnection.DEFAULT_BROKER_URL;

    private boolean transacted = false;
    private int ackMode = Session.AUTO_ACKNOWLEDGE;
    
	@Inject
	protected com.google.inject.Provider<EntityManager> emp;
	
	@Inject private UnitOfWork unitOfWork;
	@Inject
	private Injector injector;
	
	@Override
	public void run() {
		System.out.println("start consumer");
//		while(true){
//			Connection connection = null;
//			Session session = null;
//			MessageConsumer consumer = null;
//	        try {
//	        	ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, password, url);
//	        	connection = connectionFactory.createConnection();
//	        	connection.start();
//	        	session = connection.createSession(transacted, ackMode);
//	        	Destination destination = session.createQueue(ActiveMqSubject.WF_CHANGE_LOG);
//	            consumer = session.createConsumer(destination);
//	            Message m = consumer.receive(2000);
//	            
//	            if (m instanceof TextMessage) {
//	            	
////	            	[{"title":{"newVal":"abczy456567","prevVal":"abczy456","src":null},"id":"be67394f-f54d-41b5-aa11-e9171a12349d","action":"modify"}]
////	            	[{"uuid":"39cc064e-0f90-46c9-b323-7c7509b9cf54","uid":0,"title":"","note":"","path":"","dp":"nop","done":false,"position":131072,"open":false,"action":"add","mid":"39cc064e-0f90-46c9-b323-7c7509b9cf54"}]{"uuid":"39cc064e-0f90-46c9-b323-7c7509b9cf54","uid":0,"title":"","note":"","path":"","dp":"nop","done":false,"position":131072,"open":false}
////	            	[{"title":{"newVal":"1234","prevVal":"","src":null},"mid":"39cc064e-0f90-46c9-b323-7c7509b9cf54","action":"modify"}]{"title":{"newVal":"1234","prevVal":"","src":null}}
//	            	
//	            	String t  = ((TextMessage) m).getText();
//	            	JSONArray ja = JSONArray.fromObject(t);
//	            	for(int i=0;i<ja.size();i++){
//	            		JSONObject jo = ja.getJSONObject(i);
//	            		String action = jo.getString("action");
//	            		String mid = jo.getString("mid");
//	            		jo.discard("action").discard("mid");
//	            		if(jo.has("src"))jo.discard("src");
//	            		unitOfWork.begin();
//	            		try{
//		            		if("add".equals(action)){
//		            			addWfp(jo);
//		            		}else if("delete".equals(action)){
//		            			deleteWfp(jo);
//		            		}else if("modify".equals(action)){
//		            			modifyWfp(jo,mid);
//		            		}
//	            		}finally{
//	            			unitOfWork.end();
//	            		}
//	            	}
//	            	
//	            }
//	            consumer.close();
//	            session.close();
//	            connection.close();
//	        } catch (Exception e) {
//	            ;//e.printStackTrace();
//	        }finally{
//	            try {
//	                consumer.close();
//	            } catch (Throwable ignore) {
//	            }
//	            try {
//	                session.close();
//	            } catch (Throwable ignore) {
//	            }
//	            try {
//	                connection.close();
//	            } catch (Throwable ignore) {
//	            }
//	        }
//		}
	}
	
	private WorkFlowProject findWfp(String uuid){
		Query q = emp.get().createNamedQuery(WorkFlowProject.NamedQueries.FIND_PROJECT_BY_UUID);
		q.setParameter(1, uuid);
		return (WorkFlowProject) q.getSingleResult();
	}
	
//	[{"title":{"newVal":"1234","prevVal":"","src":null},"mid":"39cc064e-0f90-46c9-b323-7c7509b9cf54","action":"modify"}]{"title":{"newVal":"1234","prevVal":"","src":null}}
	@Transactional
	protected void modifyWfp(JSONObject jo, String mid) {
		WorkFlowProject wfp = findWfp(mid);
		if(wfp != null){
			for(Object k : jo.keySet()){
				if("title".equals(k)){
					wfp.setTitle(jo.getJSONObject("title").getString("newVal"));
				}else if("note".equals(k)){
					wfp.setNote(jo.getJSONObject("note").getString("newVal"));
				}else if("path".equals(k)){
					wfp.setPath(jo.getJSONObject("path").getString("newVal"));
				}else if("dp".equals(k)){
					wfp.setDp(jo.getJSONObject("dp").getString("newVal"));
				}else if("done".equals(k)){
					wfp.setDone(jo.getJSONObject("done").getBoolean("newVal"));
				}else if("position".equals(k)){
					wfp.setPosition(jo.getJSONObject("position").getLong("newVal"));
				}else if("open".equals(k)){
					wfp.setOpen(jo.getJSONObject("open").getBoolean("newVal"));
				}else if("shareType".equals(k)){
					wfp.setShareType(jo.getJSONObject("shareType").getString("newVal"));
				}else{
					
				}
			}
			wfp.setUpdatedAt(new Date());
			emp.get().merge(wfp);
		}
	}
	@Transactional
	protected void deleteWfp(JSONObject jo) {
			WorkFlowProject wfp = findWfp(jo.getString("uuid"));
			if(wfp != null){
				emp.get().remove(wfp);
			}
	}
	//	[{"uuid":"39cc064e-0f90-46c9-b323-7c7509b9cf54","uid":0,"title":"","note":"","path":"","dp":"nop","done":false,"position":131072,"open":false,"action":"add","mid":"39cc064e-0f90-46c9-b323-7c7509b9cf54"}]{"uuid":"39cc064e-0f90-46c9-b323-7c7509b9cf54","uid":0,"title":"","note":"","path":"","dp":"nop","done":false,"position":131072,"open":false}
//    uuid: {},
//    uid:{value:0},
//    title:{value:''},
//    note:{value:''},
//    path:{value:''},
//    dp:{value:Y.rootEntry},
//    done:{value:false},
//    position:{value:0},
//    open:{value:false}
	@Transactional
	protected void addWfp(JSONObject jo) {
			User creator = emp.get().find(User.class, jo.getInt("uid"));
			WorkFlowProject wfp = new WorkFlowProject();
			Date  d = new Date();
			wfp.setCreatedAt(d);
			wfp.setUpdatedAt(d);
			boolean shareTypeSetted = false;
			for(Object k : jo.keySet()){
				if("uuid".equals(k)){
					wfp.setUuid(jo.getString(k.toString()));
				}else if("uid".equals(k)){
					wfp.setCreator(creator);
				}else if("title".equals(k)){
					wfp.setTitle(jo.getString(k.toString()));
				}else if("note".equals(k)){
					wfp.setNote(jo.getString(k.toString()));
				}else if("path".equals(k)){
					wfp.setPath(jo.getString(k.toString()));
				}else if("dp".equals(k)){
					String dp = jo.getString(k.toString()); 
					wfp.setDp(dp);
//					if("nop".equalsIgnoreCase(dp)){
//						;
//					}else{
//						WorkFlowProjectDao dao = injector.getInstance(WorkFlowProjectDao.class);
//						WorkFlowProject dwp = dao.findByUUID(dp);
//						if(dwp != null){
//							wfp.setShareType(dwp.getShareType());
//							shareTypeSetted = true;
//						}
//					}
				}else if("done".equals(k)){
					wfp.setDone(jo.getBoolean(k.toString()));
				}else if("position".equals(k)){
					wfp.setPosition(jo.getLong(k.toString()));
				}else if("open".equals(k)){
					wfp.setOpen(jo.getBoolean(k.toString()));
				}else if("shareType".equals(k)){
//					if(!shareTypeSetted){
						wfp.setShareType(jo.getString(k.toString()));
//					}
				}else{
					
				}
			}
			emp.get().persist(wfp);
	}
}
